package com.yfproject.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@RestController
@RequestMapping("/ehcache")
public class EhcacheController {
	
	private static final CacheManager cacheManager = new CacheManager();
	private Cache cache;
	public EhcacheController(){
		this.cache=cacheManager.getCache("labels");
	}

	public Cache getCache() {
		return cache;
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

     /*
	 * 通过名称从缓存中获取数据
	 */
	@RequestMapping("/getCacheElement/{cacheKey}")
	public Object getCacheElement(@PathVariable String cacheKey) throws Exception {
	    Element e = cache.get(cacheKey);
		if (e == null) {
			System.out.println("未查到缓存");
			return null;
		}
		return e.getObjectValue();
	}
	/*
	 * 将对象添加到缓存中
	 */
	public void addToCache(String cacheKey, Object result) throws Exception {
		Element element = new Element(cacheKey, result);
		cache.put(element);
	}


}
